#ifndef ReceiveR_H
#define ReceiveR_H

#include <QObject>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#include "request.h"
#include <QStringList>
#include <QDateTime>

/**
 *  Receiver Object
 *  Run in HTTP Server Mode, Listen for requests on port 8369
 */

class Receiver : public QTcpServer
{
    Q_OBJECT

public:

    /**
     *  Maxmum floor The request may reach
     */
    static const int UPPER_FLOOR = 50;

    /**
     *  Start the listening of the HTTP server, if port is taken no error will be reported.
     */
    Receiver(QObject* parent = 0)
        : QTcpServer(parent)
    {
        listen(QHostAddress::Any, 8369);
    }

    /**
     *  Function triggered when a connection request is in.
     *  Accept the connection and forward it to the slot readClient.
     */
    void incomingConnection(int socket)
    {
        QTcpSocket* s = new QTcpSocket(this);
        connect(s, SIGNAL(readyRead()), this, SLOT(readClient()));
        connect(s, SIGNAL(disconnected()), this, SLOT(discardClient()));
        s->setSocketDescriptor(socket);
    }

signals:

    /**
     *  Function triggered when an avaliable is received.
     */
    void signalRequestReceived(Request* req);

private slots:

    /**
     *  Slot to parse the received data to request and return message for client.
     */
    void readClient()
    {
        QTcpSocket* socket = (QTcpSocket*)sender();
        if (socket->canReadLine()) {
            QStringList tokens = QString(socket->readLine()).split(QRegExp("[ /-\r\n]+"));
            if (tokens[0] == "GET") {
                Request* req = new Request(tokens[1].toInt(),tokens[2].toInt());
                QTextStream os(socket);
                os.setAutoDetectUnicode(true);
                if(req->getDeparture()!=0&&req->getDestination()!=0){

                    if(req->getDeparture()<=UPPER_FLOOR&&req->getDestination()<=UPPER_FLOOR){
                        os << "HTTP/1.0 200 Ok\r\n"
                              "Content-Type: text/html; charset=\"utf-8\"\r\n"
                              "\r\n"
                              "<h1>Request Received From Floor#"<<req->getDeparture()<<" to #"<<req->getDestination()<<"</h1>\n"
                           << QDateTime::currentDateTimeUtc().toString() << "\n";
                        emit signalRequestReceived(req);
                    }else{
                        os << "HTTP/1.0 200 Ok\r\n"
                              "Content-Type: text/html; charset=\"utf-8\"\r\n"
                              "\r\n"
                              "<h1>Request From Floor#"<<req->getDeparture()<<" to #"<<req->getDestination()<<" is Unavaliable <br/>"<<
                              "Avaliable Floor Number is Between #0 And #"<<UPPER_FLOOR<<"</h1>\n"
                           << QDateTime::currentDateTimeUtc().toString() << "\n";
                    }
                }else{
                    os << "HTTP/1.0 200 Ok\r\n"
                          "Content-Type: text/html; charset=\"utf-8\"\r\n"
                          "\r\n"
                          "<h1>Opps! Bad Request<br/>Usage:<br/>http://&lt;Hostname&gt;:8369/&lt;FloorFrom&gt;-&lt;FloorTo&gt;</h1>\n"
                       << QDateTime::currentDateTimeUtc().toString() << "\n";
                    delete req;
                }
                socket->close();
                if (socket->state() == QTcpSocket::UnconnectedState) {
                    delete socket;
                }
            }
        }
    }

    void discardClient()
    {
        QTcpSocket* socket = (QTcpSocket*)sender();
        socket->deleteLater();
    }

};

#endif // ReceiveR_H
